local Msg = require("core.Msg")
local ObjHuman = require("core.ObjHuman")
local FamilyExcel = require("excel.Family")
local BuildingExcel = FamilyExcel.building
local FamilyCreateConfig = FamilyExcel.create[1]
local FamilyOnHookConfig = FamilyExcel.onhookact[1]
local Lang = require("common.Lang")
local GmCommon = require("chat.GmCommon")
local RoleFFI = require("role.RoleFFI")
local FamilyDefine = require("family.FamilyDefine")
local InnerDataManagerFL = require("innerdata.InnerDataManagerFL")
local InnerDataDefine = require("innerdata.Define")
local Obj = require("core.Obj")
local Grid = require("bag.Grid")
local BagLogic = require("bag.BagLogic")
local Util = require("common.Util")
local ContributionExcel = FamilyExcel.contribution
local BannerExcel = FamilyExcel.banner
local ShopExcel = FamilyExcel.shop
local StrategyExcel = FamilyExcel.strategy
local ItemDefine = require("bag.ItemDefine")
local ActivityLogicL = require("activity.ActivityLogicL")
local VipLogic = require("vip.VipLogic")
local VipConfig = require("excel.Vip").vip
local VipDefine = require("vip.VipDefine")
local CopyHandler = require("copy.HandlerL")
local CopyDefine = require("copy.Define")
local ShopHelp = require("shop.ShopHelp")
local CopyCommon = require("copy.CopyCommon")
local FamilyLogicFL = require("family.FamilyLogicFL")
local Broadcast = require("broadcast.Broadcast")
local OfficialLogic = require("official.OfficialLogic")

RandomShop = RandomShop or {}

--军团创建
function CG_FAMILY_CREATE(human, msg)
    if msg.createType ~= 0 and msg.createType ~= 1 then
        return
    end

    local msgErr = Msg.gc.GC_BROADCAST
    msgErr.type = Lang.MOUSE

    local familyNameLen = string.len(msg.familyName)
    if familyNameLen <= 0 or familyNameLen > 24 then
        msgErr.msg = Lang.FAMILY_NAME_LEN_INVALID
        Msg.send(msgErr, human.fd)
        return
    end

    if GmCommon.filter_name(msg.familyName) ~= msg.familyName then
        msgErr.msg = Lang.FAMILY_NAME_WORD_INVALID
        Msg.send(msgErr, human.fd)
        return
    end

    local uuid = RoleFFI.ffi_string(human.db.familyUuid)
    if string.len(uuid) > 0 then
        msgErr.msg = Lang.FAMILY_CREATE_MUST_EXIT_FAMILY
        Msg.send(msgErr, human.fd)
        return
    end

    if (os.time() - human.db.familyExitTime) < FamilyDefine.FAMILY_EXITTIME then
        msgErr.msg = Lang.FAMILY_CREATE_NEED_NEXT_DAY
        Msg.send(msgErr, human.fd)
        return
    end

    if human.db.lv < FamilyCreateConfig.createMinLv then
        msgErr.msg = string.format(Lang.FAMILY_CREATE_LV_NOT_ENOUGH, FamilyCreateConfig.createMinLv)
        Msg.send(msgErr, human.fd)
        return
    end

    if msg.createType == 0 then
        if ObjHuman.getYinliang(human) < FamilyCreateConfig.needYinliang then
            msgErr.msg = Lang.FAMILY_CREATE_YINLIANG_NOT_ENOUGH
            Msg.send(msgErr, human.fd)
            return
        end
        human.db.precost_yinliang  = human.db.precost_yinliang + FamilyCreateConfig.needYinliang
    else
        if ObjHuman.getYuanbao(human) < FamilyCreateConfig.yuanbao then
            msgErr.msg = Lang.FAMILY_CREATE_YUANBAO_NOT_ENOUGH
            Msg.send(msgErr, human.fd)
            return
        end
        human.db.precost_yuanbao = human.db.precost_yuanbao + FamilyCreateConfig.yuanbao
    end
    local wMsg = Msg.lw.LW_FAMILY_CREATE
    wMsg.createType = msg.createType
    wMsg.familyName = msg.familyName
    Msg.send2world(wMsg, human._id)
end


function WL_FAMILY_CREATE_FAILED()
end

function CG_FAMILY_OPEN(human)
    local nMsg = Msg.gc.GC_FAMILY_OPEN
    nMsg.result = 0
    nMsg.yinliang = FamilyCreateConfig.needYinliang
    nMsg.yuanbao = FamilyCreateConfig.yuanbao
    nMsg.contributiondata[0] = 0
    for k, v in pairs(ContributionExcel) do
        nMsg.contributiondata[0] = nMsg.contributiondata[0] + 1
        local nData = nMsg.contributiondata[nMsg.contributiondata[0]]
        nData.type = v.type
        nData.addexp = v.addexp
        nData.addmoney = v.addmoney
        nData.addcontribution = v.addcontribution
            local cache = {}
            Grid.create(cache, k, 1, false)
            Grid.makeItem(cache, nData.itemData, 0)
    end

    nMsg.bannerconfiglist[0] = 0
    for k, v in ipairs(BannerExcel) do
        nMsg.bannerconfiglist[0] = nMsg.bannerconfiglist[0] + 1
        local nData = nMsg.bannerconfiglist[nMsg.bannerconfiglist[0]]
        nData.needmoney = v.needmoney
        nData.desc = ""
        nData.itemlist[0] = 0
        for kk, vv in ipairs(v.itemdata) do
            nData.itemlist[0] = nData.itemlist[0] + 1
            local cache = {}
            Grid.create(cache, vv[1], vv[2], false)
            Grid.makeItem(cache, nData.itemlist[nData.itemlist[0]], 0)
        end

        nData.attrlist[0] = 0
        for kk, vv in ipairs(v.addattr) do
            nData.attrlist[0] = nData.attrlist[0] + 1
            local nAttrData = nData.attrlist[nData.attrlist[0]]
            nAttrData.key = vv[1]
            nAttrData.value = vv[2]
        end
    end
    
    nMsg.lvUpNeedMoney = BuildingExcel[human.db.familyLv] and BuildingExcel[human.db.familyLv].needMoney or 0
    nMsg.maxContributionRmb = FamilyCreateConfig.maxContributionRmb
    nMsg.algContributionRmb = human.db.familyAlgContributionRmb
    Msg.send(nMsg, human.fd)
    sendFamilyInviteFlag(human)
end

function CG_FAMILY_SETINVITE(human, msg)
    if msg.flag ~= 0 and msg.flag ~= 1 then
        return
    end
    human.db.familyReject = msg.flag
    sendFamilyInviteFlag(human)
end

function sendFamilyInviteFlag(human)
    local nSendMsg = Msg.gc.GC_FAMILY_SETINVITE
    nSendMsg.flag = human.db.familyReject
    Msg.send(nSendMsg, human.fd)
end

-- 军团仓库add物品
function CG_FAMILY_STORE_ITEM_ADD(human, msg)
    local msgErr = Msg.gc.GC_BROADCAST
    msgErr.type = Lang.MOUSE
    local bagIndex = msg.bagIndex
    local bagIndexOK = BagLogic.checkIndex(human, bagIndex)
    if not bagIndexOK then
        msgErr.msg = Lang.FAMILY_STORE_BAG_INDEX_INVALID
        Msg.send(msgErr, human.fd)
        return
    end

    local bagGrid = BagLogic.getGridByIndex(human, bagIndex)
    if not bagGrid then
        msgErr.msg = Lang.FAMILY_STORE_BAG_ITEM_NOT_EXIST
        Msg.send(msgErr, human.fd)
        return
    end

    if ItemDefine.getValue(bagGrid.id, "canStore") == 1 then
        return false
    end

    if bagGrid.bind == 1 then
        msgErr.msg = Lang.FAMILY_STORE_BAG_ITEM_BIND
        Msg.send(msgErr, human.fd)
        return
    end

    local nMsgData = Msg.gc.GC_FAMILY_STORE_ITEM_CHANGE
    Grid.makeItem(bagGrid, nMsgData.itemData)

    local nGridData = {}
    Grid.copy(nGridData, bagGrid, true)
    local nSend2Ldata = {
        type = 5,
        data = {bagGrid = nGridData, bagIndex = bagIndex}
    }
    InnerDataManagerFL.Send2WInnerData(human, InnerDataDefine.INNERDATA_TYPE_FAMILY, nSend2Ldata)
end

-- 军团仓库提取
function CG_FAMILY_STORE_ITEM_GET(human, msg)
    local bagIndex = msg.bagIndex
    local storeIndex = msg.storeIndex
    local cnt = msg.cnt

    local msgErr = Msg.gc.GC_BROADCAST
    msgErr.type = Lang.MOUSE

    if human.familyUuid == "" then
        msgErr.msg = Lang.FAMILY_NOT_EXIST
        Msg.send(msgErr, human.fd)
        return
    end

    local leftCap = BagLogic.getLeftGrids(human)
    if leftCap == 0 then
        msgErr.msg = Lang.FAMILY_STORE_BAG_CAP_NOT_ENOUGH
        Msg.send(msgErr, human.fd)
        return
    end

    local bagIndexOK = BagLogic.checkIndex(human, bagIndex)
    if not bagIndexOK then
        msgErr.msg = Lang.FAMILY_STORE_BAG_INDEX_INVALID
        Msg.send(msgErr, human.fd)
        return
    end

    local bagGrid = BagLogic.getGridByIndex(human, bagIndex)
    if bagGrid then
        bagIndex = BagLogic.getEmptyIndex(human)
        if not bagIndex then
            assert()
        end
    end

    local bagGrid = BagLogic.getGridByIndex(human, bagIndex)
    if bagGrid.id ~= 0 then
        msgErr.msg = Lang.FAMILY_STORE_BAG_INDEX_INVALID
        Msg.send(msgErr, human.fd)
        return
    end

    local nSend2Ldata = {
        type = 6,
        data = {storeIndex = storeIndex, cnt = cnt, bagIndex = bagIndex}
    }
    InnerDataManagerFL.Send2WInnerData(human, InnerDataDefine.INNERDATA_TYPE_FAMILY, nSend2Ldata)
end

function CG_FAMILY_STRATEGY_QUERY(human)
    local nMsg = Msg.gc.GC_FAMILY_STRATEGY_QUERY
    nMsg.strategylist[0] = 0
    local curlv = 0
    local nCeilLv = (human.db.familyLv or 0) * 2
    for k, v in ipairs(StrategyExcel) do
        nMsg.strategylist[0] = nMsg.strategylist[0] + 1
        local nData = nMsg.strategylist[nMsg.strategylist[0]]
        nData.id = k
        nData.name = v.name
        nData.icon = v.icon
        curlv = human.db.familyStrategyList[k - 1].strategyLev
        curlv = curlv > nCeilLv and nCeilLv or curlv
        nData.curlv = curlv
        nData.nextneedmoney = 0
        nData.curattrlist[0] = 0
        local curstrateAttr = v.strategydata[nData.curlv]
        if curstrateAttr then
            for k, v in ipairs(curstrateAttr[3]) do
                nData.curattrlist[0] = nData.curattrlist[0] + 1
                local nCurAttrData = nData.curattrlist[nData.curattrlist[0]]
                nCurAttrData.key = v[1]
                nCurAttrData.value = v[2]
            end
        end

        nData.nextattrlist[0] = 0
        local nextstrateAttr = v.strategydata[nData.curlv + 1]
        if nextstrateAttr then
            for k, v in ipairs(nextstrateAttr[3]) do
                nData.nextattrlist[0] = nData.nextattrlist[0] + 1
                local nNextAttrData = nData.nextattrlist[nData.nextattrlist[0]]
                nNextAttrData.key = v[1]
                nNextAttrData.value = v[2]
            end
            nData.nextneedcontribution = nextstrateAttr[2]
        end
    end
    Msg.send(nMsg, human.fd)
end

function CG_FAMILY_STRATEGY_UP(human, msg)
    local msgErr = Msg.gc.GC_BROADCAST
    msgErr.type = Lang.MOUSE
    if human.familyUuid == "" then
        msgErr.msg = Lang.FAMILY_NOT_EXIST
        Msg.send(msgErr, human.fd)
        return
    end

    local nStrategyConfigData = StrategyExcel[msg.id]
    if nStrategyConfigData then
        local nStrategyData = human.db.familyStrategyList[msg.id - 1]
        if not nStrategyData or nStrategyData.strategyLev >= (human.db.familyLv * 2) then
            msgErr.msg = Lang.FAMILY_STRATEGY_LVMAX_FAMILYLV
            Msg.send(msgErr, human.fd)
            return
        end

        if human.db.familyContribution < nStrategyConfigData.strategydata[nStrategyData.strategyLev + 1][2] then
            msgErr.msg = Lang.FAMILY_CONTRIBUTION_NOT_ENOUGH
            Msg.send(msgErr, human.fd)
            return
        end

        nStrategyData.strategyLev = nStrategyData.strategyLev + 1

        local nMsg = Msg.gc.GC_FAMILY_STRATEGY_UP
        nMsg.result = 0
        nMsg.id = msg.id
        nMsg.curlv = nStrategyData.strategyLev
        nMsg.nextattrlist[0] = 0
        nMsg.nextneedcontribution = 0
        local nextstrateAttr = nStrategyConfigData.strategydata[nMsg.curlv + 1]
        if nextstrateAttr then
            for k, v in ipairs(nextstrateAttr[3]) do
                nMsg.nextattrlist[0] = nMsg.nextattrlist[0] + 1
                local nNextAttrData = nMsg.nextattrlist[nMsg.nextattrlist[0]]
                nNextAttrData.key = v[1]
                nNextAttrData.value = v[2]
            end
            nMsg.nextneedcontribution = nextstrateAttr[2]
        end
        Msg.send(nMsg, human.fd)

        updateFamilyContribution(human, -(nStrategyConfigData.strategydata[nStrategyData.strategyLev][2]))

        local msgRet = Msg.gc.GC_FAMILY_ADD_CONTRIBUTION
        msgRet.contribution = -(nStrategyConfigData.strategydata[nStrategyData.strategyLev][2])
        Msg.send(msgRet, human.fd)

        ObjHuman.doCalc(human)
    end
end

--军团捐献
function CG_FAMILY_CONTRIBUTE(human, msg)
    if msg.type == 1 then
        local msgErr = Msg.gc.GC_BROADCAST
        msgErr.type = Lang.MOUSE

        if human.familyUuid == "" then
            msgErr.msg = Lang.FAMILY_NOT_EXIST
            Msg.send(msgErr, human.fd)
            return
        end

        local nItemData = {}
        local nSumExp = 0
        local nSumMoney = 0
        local nSumContribution = 0
        for k, v in pairs(ContributionExcel) do
            if v.type == 1 then
                local num = BagLogic.getItemCount(human, k)
                if num > 0 then
                    local addmoney = num * ContributionExcel[k].addmoney
                    local addexp = num * ContributionExcel[k].addexp
                    local addcontribution = num * ContributionExcel[k].addcontribution
                    nSumExp = nSumExp + addexp
                    nSumMoney = nSumMoney + addmoney
                    nSumContribution = nSumContribution + addcontribution
                    table.insert(nItemData, {k, num, addmoney, addexp, addcontribution})
                end
            end
        end

        if #nItemData <= 0 then
            msgErr.msg = Lang.FAMILY_CONTRIBUTE_ITEM_NOT_ENOUGH
            Msg.send(msgErr, human.fd)
            return
        end

        local nSend2Ldata = {
            type = 7,
            data = {addmoney = nSumMoney, addexp = nSumExp, addcontribution = nSumContribution}
        }
        InnerDataManagerFL.Send2WInnerData(human, InnerDataDefine.INNERDATA_TYPE_FAMILY, nSend2Ldata)

        --if human.db.familyContribution + nSumContribution > CreateExcel[1].familyContributionMax then
        --    msgErr.msg = Lang.FAMILY_CONTRIBUTION_MAX_NUM
        --    Msg.send(msgErr, human.fd)
        --end

        updateFamilyContribution(human, nSumContribution)

        if nSumContribution > 0 then
            local msgRet = Msg.gc.GC_FAMILY_ADD_CONTRIBUTION
            msgRet.contribution = nSumContribution
            Msg.send(msgRet, human.fd)
        end

        msgErr.msg = string.format(Lang.FAMILY_CONTRIBUTE_OK, nSumContribution)
        Msg.send(msgErr, human.fd)

        if nSumContribution > 0 then
            --Log.write(Log.LOGID_OSS_FAMILY_CONTRIBUTION_GET_AND_USE, human._id, human.db.account, human.name, human.db.lv, family._id, family.familyName, family.familyLv, addContribution, 0, LogDefine.FAMILY_CONTRIBUTION_ACTION.GET_CONTRIBUTE)
        end

        ActivityLogicL.updateActivityValue(human, "family_give")

        for k, v in ipairs(nItemData) do
            BagLogic.delItemsById(human, v[1], v[2], "familyContribution")
        end
    elseif msg.type == 2 then
        local msgErr = Msg.gc.GC_BROADCAST
        msgErr.type = Lang.MOUSE

        if human.familyUuid == "" then
            msgErr.msg = Lang.FAMILY_NOT_EXIST
            Msg.send(msgErr, human.fd)
            return
        end

        local nItemData = {}
        local nSumContribution = 0
        for k, v in pairs(ContributionExcel) do
            if v.type == 2 then
                local num = BagLogic.getItemCount(human, k)
                if num > 0 then
                    local addcontribution = num * ContributionExcel[k].addcontribution
                    nSumContribution = nSumContribution + addcontribution
                    table.insert(nItemData, {k, num, addcontribution})
                end
            end
        end

        if #nItemData <= 0 then
            msgErr.msg = Lang.FAMILY_CONTRIBUTE_ITEM_NOT_ENOUGH
            Msg.send(msgErr, human.fd)
            return
        end

        local nSend2Ldata = {
            type = 9,
            data = {addcontribution = nSumContribution, itemData = nItemData}
        }
        InnerDataManagerFL.Send2WInnerData(human, InnerDataDefine.INNERDATA_TYPE_FAMILY, nSend2Ldata)

        --if human.db.familyContribution + nSumContribution > CreateExcel[1].familyContributionMax then
        --    msgErr.msg = Lang.FAMILY_CONTRIBUTION_MAX_NUM
        --    Msg.send(msgErr, human.fd)
        --end

        updateFamilyContribution(human, nSumContribution)

        if nSumContribution > 0 then
            local msgRet = Msg.gc.GC_FAMILY_ADD_CONTRIBUTION
            msgRet.contribution = nSumContribution
            Msg.send(msgRet, human.fd)
        end

        msgErr.msg = string.format(Lang.FAMILY_CONTRIBUTE_OK, nSumContribution)
        Msg.send(msgErr, human.fd)

        ActivityLogicL.updateActivityValue(human, "family_flag")
        if nSumContribution > 0 then
            --Log.write(Log.LOGID_OSS_FAMILY_CONTRIBUTION_GET_AND_USE, human._id, human.db.account, human.name, human.db.lv, family._id, family.familyName, family.familyLv, addContribution, 0, LogDefine.FAMILY_CONTRIBUTION_ACTION.GET_CONTRIBUTE)
        end

        for k, v in ipairs(nItemData) do
            BagLogic.delItemsById(human, v[1], v[2], "familyContribution")
        end
    elseif msg.type == 3 then
        local msgErr = Msg.gc.GC_BROADCAST
        msgErr.type = Lang.MOUSE

        if human.familyUuid == "" then
            msgErr.msg = Lang.FAMILY_NOT_EXIST
            Msg.send(msgErr, human.fd)
            return
        end

        if msg.rmbNum <= 0 then
            return
        end


        local nRealRmbNum = math.min(msg.rmbNum, (FamilyCreateConfig.maxContributionRmb - human.db.familyAlgContributionRmb)) 
        if nRealRmbNum <= 0 then
            msgErr.msg = Lang.FAMILY_CONTRIBUTE_RMBMAX
            Msg.send(msgErr, human.fd)
            return
        end

        local nRmbNum = ObjHuman.getYuanbao(human)
        if nRealRmbNum > nRmbNum then
            msgErr.msg = Lang.FAMILY_CONTRIBUTE_NOT_RMB
            Msg.send(msgErr, human.fd)
            return
        end

        local nSumExp = 0
        local nSumMoney = 0
        local nSumContribution = 0
        for k, v in pairs(ContributionExcel) do
            if v.type == 3 then
                nSumMoney = nSumMoney + ContributionExcel[k].addmoney
                nSumExp = nSumExp + ContributionExcel[k].addexp
                nSumContribution = nSumContribution + ContributionExcel[k].addcontribution
            end
        end

        nSumMoney = nRealRmbNum * nSumMoney
        nSumExp = nRealRmbNum * nSumExp
        nSumContribution = nRealRmbNum * nSumContribution

        local nSend2Ldata = {
            type = 7,
            data = {addmoney = nSumMoney, addexp = nSumExp, addcontribution = nSumContribution}
        }
        InnerDataManagerFL.Send2WInnerData(human, InnerDataDefine.INNERDATA_TYPE_FAMILY, nSend2Ldata)
        human.db.familyAlgContributionRmb = human.db.familyAlgContributionRmb + nRealRmbNum
        ObjHuman.decYuanbao(human, nRealRmbNum, "familyContribution")

        --if human.db.familyContribution + nSumContribution > CreateExcel[1].familyContributionMax then
        --    msgErr.msg = Lang.FAMILY_CONTRIBUTION_MAX_NUM
        --    Msg.send(msgErr, human.fd)
        --end

        updateFamilyContribution(human, nSumContribution)

        if nSumContribution > 0 then
            local msgRet = Msg.gc.GC_FAMILY_ADD_CONTRIBUTION
            msgRet.contribution = nSumContribution
            Msg.send(msgRet, human.fd)
        end

        msgErr.msg = string.format(Lang.FAMILY_CONTRIBUTE_OK, nSumContribution)
        Msg.send(msgErr, human.fd)

        if nSumContribution > 0 then
            --Log.write(Log.LOGID_OSS_FAMILY_CONTRIBUTION_GET_AND_USE, human._id, human.db.account, human.name, human.db.lv, family._id, family.familyName, family.familyLv, addContribution, 0, LogDefine.FAMILY_CONTRIBUTION_ACTION.GET_CONTRIBUTE)
        end

        ActivityLogicL.updateActivityValue(human, "family_give")
    end
end

--设置军团贡献
function updateFamilyContribution(human, d, send)
    --勋章满级增加经验
    --if isMwbd and human.db.medalData and human.db.medalData[MedalDefine.KEY_MOWUBAODONG] and human.db.medalData[MedalDefine.KEY_MOWUBAODONG].isFullLv and human.db.medalData[MedalDefine.KEY_MOWUBAODONG].isFullLv == 1 then
    --    d = math.ceil(d * 1.2)
    --end

    --d = math.floor(d)

    --if d == 0 then
    --    return
    --end

    local val = human.db.familyContribution + d
    --if val < 0 then
    --    assert()
    --end
    human.db.familyContribution = val < 0 and 0 or val
    if send then
        local msgRet = Msg.gc.GC_FAMILY_ADD_CONTRIBUTION
        msgRet.contribution = d
        Msg.send(msgRet, human.fd)
    end
end

function OnRandomShop(randomShop)
    return math.random(1, #randomShop)
end

function OnFlushFamilyShop(human, systemFlush)
    if human.familyUuid == "" then
        return
    end
    local nRandomShop = {}
    Util.copyTable(RandomShop, nRandomShop)
    local nTemp = {}
    human.db.familyShopListLen = 0
    local nLen = 0
    for k, v in ipairs(ShopExcel) do
        if nLen >= FamilyCreateConfig.shopcnt or human.db.familyShopListLen > 100 then
            break
        end

        if v.type == 1 then
            nTemp = k
        else
            local nIndex = math.random(1, #nRandomShop)
            nTemp = nRandomShop[nIndex].index
            table.remove(nRandomShop, nIndex)
        end
        human.db.familyShopList[human.db.familyShopListLen].index = nTemp
        human.db.familyShopList[human.db.familyShopListLen].state = 0
        human.db.familyShopListLen = human.db.familyShopListLen + 1
        nLen = nLen + 1
    end

    if systemFlush then
        human.db.familyContributionShopFlushTime = os.time()
        human.db.familyShopFlushCnt = 0
    end
end

--军团商店请求
function CG_FAMILY_SHOP_QUERY(human, systemCheck)
    local msgErr = Msg.gc.GC_BROADCAST
    msgErr.type = Lang.MOUSE
    if human.familyUuid == "" and not systemCheck then
        msgErr.msg = Lang.FAMILY_NOT_EXIST
        Msg.send(msgErr, human.fd)
        return
    end

    if not Util.isSameDay(human.db.familyContributionShopFlushTime) or human.db.familyShopListLen == 0 then
        OnFlushFamilyShop(human, true)
    end

    local msgRet = Msg.gc.GC_FAMILY_SHOP_QUERY
    msgRet.flushcontributionshopcnt = human.db.familyShopFlushCnt
    msgRet.flushcontributionshopconfig[0] = 0
    for k, v in ipairs(FamilyCreateConfig.flushcontributionshop) do
        msgRet.flushcontributionshopconfig[0] = msgRet.flushcontributionshopconfig[0] + 1
        msgRet.flushcontributionshopconfig[k] = v
    end
    msgRet.shopitems[0] = 0
    for i = 0, human.db.familyShopListLen - 1 do
        msgRet.shopitems[0] = msgRet.shopitems[0] + 1
        local nData = msgRet.shopitems[msgRet.shopitems[0]]
        local nIndex = human.db.familyShopList[i].index
        local nConfigData = ShopExcel[nIndex]
        if nConfigData then
            nData.needContribution = nConfigData.needcontribution
            nData.state = human.db.familyShopList[i].state
            local nGrid = {}
            Grid.create(nGrid, nConfigData.itemid, nConfigData.num)
            Grid.makeItem(nGrid, nData.itemData, 0)
        end
    end
    Msg.send(msgRet, human.fd)
end


--军团商店购买商品
function CG_FAMILY_SHOP_BUY(human, msg)
    local msgErr = Msg.gc.GC_BROADCAST
    msgErr.type = Lang.MOUSE
    if human.familyUuid == "" then
        msgErr.msg = Lang.FAMILY_NOT_EXIST
        Msg.send(msgErr, human.fd)
        return
    end

    local nBuyGridIndex = msg.index
    if nBuyGridIndex < 0 or nBuyGridIndex > human.db.familyShopListLen then
        return
    end

    if human.db.familyShopList[nBuyGridIndex].state == 1 then
        return
    end

    local nConfigDataIndex = human.db.familyShopList[nBuyGridIndex].index
    local nShopItemConfigData = ShopExcel[nConfigDataIndex]
    if nShopItemConfigData then
        if nShopItemConfigData.needcontribution > human.db.familyContribution then
            msgErr.msg = Lang.FAMILY_SHOP_BUY_CONTRIBUTION_NOT_ENOUGTH
            Msg.send(msgErr, human.fd)
            return
        end

        if ItemDefine.isEquip(nShopItemConfigData.itemid) then
            --if cnt > 1 then
            --    msgErr.msg = Lang.FAMILY_SHOP_BUY_CNT_INVALID
            --    Msg.send(msgErr, human.fd)
            --    return
            --end
        end

        local canAdd = BagLogic.checkCanAddItem(human, nShopItemConfigData.itemid, true, nShopItemConfigData.num)
        if not canAdd then
            return
        end

        --local canBuy = nil
        --if conf.cnt > 0 then
        --    canBuy = canBuyItem(human, cnt, conf)
        --    if not canBuy then
        --        msgErr.msg = Lang.FAMILY_SHOP_BUY_CNT_INVALID
        --        Msg.send(msgErr, human.fd)
        --        return
        --    end
        --end
        human.db.familyShopList[nBuyGridIndex].state = 1

        msgErr.msg = Lang.FAMILY_SHOP_BUY_OK
        Msg.send(msgErr, human.fd)

        updateFamilyContribution(human, -nShopItemConfigData.needcontribution)
        if nShopItemConfigData.needcontribution > 0 then
            local msgRet = Msg.gc.GC_FAMILY_ADD_CONTRIBUTION
            msgRet.contribution = -nShopItemConfigData.needcontribution
            Msg.send(msgRet, human.fd)
        end

        if ItemDefine.isEquip(nShopItemConfigData.itemid) then
            local nGridData = Grid.create(nil, nShopItemConfigData.itemid, nShopItemConfigData.num, true)
            BagLogic.addItemByGrid(human, nil, nGridData, "family_contributionshop_buy")
        else
            BagLogic.addItem(human, nShopItemConfigData.itemid, true, nShopItemConfigData.num, "family_contributionshop_buy")
        end

        local msgRet = Msg.gc.GC_FAMILY_SHOP_BUY
        msgRet.index = nBuyGridIndex
        Msg.send(msgRet, human.fd)

        --Log.write(Log.LOGID_OSS_FAMILY_CONTRIBUTION_GET_AND_USE, human._id, human.db.account, human.name, human.db.lv, family._id, family.familyName, family.familyLv, cnt, conf.itemID, LogDefine.FAMILY_CONTRIBUTION_ACTION.USE_BUY)
    else
        msgErr.msg = Lang.FAMILY_SHOP_GOODS_ID_INVALID
        Msg.send(msgErr, human.fd)
        return
    end
end

function CG_FAMILY_SHOP_FLUSH(human)
    local msgErr = Msg.gc.GC_BROADCAST
    msgErr.type = Lang.MOUSE
    if human.familyUuid == "" then
        msgErr.msg = Lang.FAMILY_NOT_EXIST
        Msg.send(msgErr, human.fd)
        return
    end

    local nShopFlushCnt = (human.db.familyShopFlushCnt + 1) > #FamilyCreateConfig.flushcontributionshop and #FamilyCreateConfig.flushcontributionshop or (human.db.familyShopFlushCnt + 1)

    local nNeedContribution = FamilyCreateConfig.flushcontributionshop[nShopFlushCnt]

    if nNeedContribution > human.db.familyContribution then
        msgErr.msg = Lang.FAMILY_SHOP_FLUSH_CONTRIBUTION_NOT_ENOUGTH
        Msg.send(msgErr, human.fd)
        return
    end

    human.db.familyShopFlushCnt = human.db.familyShopFlushCnt + 1
    human.db.familyShopListLen = 0
    OnFlushFamilyShop(human)
    updateFamilyContribution(human, -(nNeedContribution))

    if nNeedContribution > 0 then
        local msgRet = Msg.gc.GC_FAMILY_ADD_CONTRIBUTION
        msgRet.contribution = -nNeedContribution
        Msg.send(msgRet, human.fd)
    end

    local msgRet = Msg.gc.GC_FAMILY_SHOP_QUERY
    msgRet.flushcontributionshopcnt = human.db.familyShopFlushCnt
    msgRet.flushcontributionshopconfig[0] = 0
    for k, v in ipairs(FamilyCreateConfig.flushcontributionshop) do
        msgRet.flushcontributionshopconfig[0] = msgRet.flushcontributionshopconfig[0] + 1
        msgRet.flushcontributionshopconfig[k] = v
    end
    msgRet.shopitems[0] = 0
    for i = 0, human.db.familyShopListLen - 1 do
        msgRet.shopitems[0] = msgRet.shopitems[0] + 1
        local nData = msgRet.shopitems[msgRet.shopitems[0]]
        local nIndex = human.db.familyShopList[i].index
        local nConfigData = ShopExcel[nIndex]
        if nConfigData then
            nData.needContribution = nConfigData.needcontribution
            nData.state = human.db.familyShopList[i].state
            local nGrid = {}
            Grid.create(nGrid, nConfigData.itemid, nConfigData.num)
            Grid.makeItem(nGrid, nData.itemData, 0)
        end
    end
    Msg.send(msgRet, human.fd)
end

function CG_FAMILY_ACT_QUERY(human, msg)
    local msgErr = Msg.gc.GC_BROADCAST
    msgErr.type = Lang.MOUSE
    if human.familyUuid == "" then
        msgErr.msg = Lang.FAMILY_NOT_EXIST
        Msg.send(msgErr, human.fd)
        return false
    end

    local nType = msg.type
    if nType == 1 then
        if ObjHuman.getLv(human) < 25 then
            msgErr.msg = Lang.FAMILY_ACT_ONHOOK_NOLV
            Msg.send(msgErr, human.fd)
            return false
        end

        local nSendMsg = Msg.gc.GC_FAMILY_ACT_ONHOOK
        nSendMsg.freeTime = FamilyOnHookConfig.freeTime
        nSendMsg.clearTime = FamilyOnHookConfig.clearTime
        nSendMsg.remainTime = onGetOnHookLeftTime(human)
        nSendMsg.algBuyTime = human.db.familyOnHookBuyTime
        local nGrid = {}
        nSendMsg.rewardItem[0] = 0
        for k, v in ipairs(FamilyOnHookConfig.reward) do
            nSendMsg.rewardItem[0] = nSendMsg.rewardItem[0] + 1
            local nRewarData = nSendMsg.rewardItem[nSendMsg.rewardItem[0]]
            Grid.create(nGrid, v[1], v[2])
            Grid.makeItem(nGrid, nRewarData)
        end
        nSendMsg.bgID = FamilyOnHookConfig.bgID
        nSendMsg.buyTimeRmb = FamilyOnHookConfig.buyTimeRmb
        nSendMsg.vipTimeList[0] = 0
        for k, v in ipairs(VipConfig) do
            nSendMsg.vipTimeList[0] = nSendMsg.vipTimeList[0] + 1
            local nVipTimeData = nSendMsg.vipTimeList[nSendMsg.vipTimeList[0]]
            nVipTimeData.vipLv = k
            nVipTimeData.addTime = v.familyOnHook
        end
        Msg.send(nSendMsg, human.fd)
    elseif nType == 2 then
        local nSendMsg = Msg.gc.GC_FAMILY_ACT_COPY
        nSendMsg.copyID = CopyDefine.COPY_FAMILY_COPY_ID[1]
        nSendMsg.rewardItem[0] = 0
        nSendMsg.rewardItem2[0] = 0
        local itemCount, itemGrids = CopyHandler.getRewardItem(CopyDefine.COPY_FAMILY_COPY_ID[1])
        for i = 1, itemCount do
            nSendMsg.rewardItem[0] = nSendMsg.rewardItem[0] + 1
            Grid.makeItem(itemGrids[i], nSendMsg.rewardItem[i], 0)
            if i == 10 then
                break
            end
        end
        itemCount, itemGrids = CopyHandler.getRewardItem(CopyDefine.COPY_FAMILY_COPY_ID[2])
        for i = 1, itemCount do
            nSendMsg.rewardItem2[0] = nSendMsg.rewardItem2[0] + 1
            Grid.makeItem(itemGrids[i], nSendMsg.rewardItem2[i], 0)
            if i == 10 then
                break
            end
        end
        Msg.send(nSendMsg, human.fd)
        local nSend2Ldata = {
            type = 11,
            data = {}
        }
        InnerDataManagerFL.Send2WInnerData(human, InnerDataDefine.INNERDATA_TYPE_FAMILY, nSend2Ldata)
    end
end

function CG_FAMILY_ACT_ONHOOKBUY(human, msg)
    local msgErr = Msg.gc.GC_BROADCAST
    msgErr.type = Lang.MOUSE
    if human.familyUuid == "" then
        msgErr.msg = Lang.FAMILY_NOT_EXIST
        Msg.send(msgErr, human.fd)
        return false
    end

    local nVipLv = VipLogic.getVipLv(human)
    if nVipLv <= 0 then
        msgErr.msg = Lang.FAMILY_ACT_ONHOOK_NOVIP
        Msg.send(msgErr, human.fd)
        return false
    end

    local nBuyTimes = math.ceil(tonumber(msg.time))
    if nBuyTimes <= 0 then
        return
    end

    local nCanBuyTime = onGetOnHookBuyTime(human, nVipLv)
    if human.db.familyOnHookBuyTime + nBuyTimes > nCanBuyTime then
        msgErr.msg = Lang.FAMILY_ACT_ONHOOK_NOBUY
        Msg.send(msgErr, human.fd)
        return false
    end

    local nDayEndTime = Util.remainDaySeconds()
    if (FamilyOnHookConfig.freeTime + human.db.familyOnHookBuyTime * 3600 - human.db.familyOnHookTime) + nBuyTimes * 3600 > nDayEndTime then
        msgErr.msg = Lang.FAMILY_ACT_ONHOOK_MOREDAY
        Msg.send(msgErr, human.fd)
        return false
    end

    if ObjHuman.getYuanbao(human) < (FamilyOnHookConfig.buyTimeRmb * nBuyTimes) then
        msgErr.msg = Lang.FAMILY_ACT_ONHOOK_NORMB
        Msg.send(msgErr, human.fd)
        return false
    end

    human.db.familyOnHookBuyTime = human.db.familyOnHookBuyTime + nBuyTimes
    ObjHuman.decYuanbao(human, FamilyOnHookConfig.buyTimeRmb * nBuyTimes, "familyonhook")
    msgErr.msg = Lang.FAMILY_ACT_ONHOOK_SUCESS
    Msg.send(msgErr, human.fd)
    onSendOnHookTime(human)
    local nSendMsg = Msg.gc.GC_FAMILY_ACT_ONHOOKBUY
    nSendMsg.result = 0
    nSendMsg.algBuyTime = human.db.familyOnHookBuyTime
    Msg.send(nSendMsg, human.fd)
    return true
end

function CG_FAMILY_ACT_YB_COPY_START(human, msg)
    local msgErr = Msg.gc.GC_BROADCAST
    msgErr.type = Lang.MOUSE
    if human.familyUuid == "" then
        msgErr.msg = Lang.FAMILY_NOT_EXIST
        Msg.send(msgErr, human.fd)
        return false
    end
    if ObjHuman.getYuanbao(human) < FamilyDefine.FAMILY_COPY_YUANBAO then
        msgErr.msg = Lang.OFFLINE_PK_NO_RMB_FOR_CD
        Msg.send(msgErr, human.fd)
        ShopHelp.onNoRMB(human)
        return false
    end
    local err = CopyCommon.checkEnterCondition(human, CopyDefine.COPY_FAMILY_COPY_ID[2])
    if err then
        msgErr.msg = err
        Msg.send(msgErr, human.fd)
        return
    end
    human.db.precost_yuanbao = human.db.precost_yuanbao + FamilyDefine.FAMILY_COPY_YUANBAO 
    local nSend2Ldata = {
            type = 12,
    }
    InnerDataManagerFL.Send2WInnerData(human, InnerDataDefine.INNERDATA_TYPE_FAMILY, nSend2Ldata)
    
end


function CG_FAMILY_ACT_TY_GIVE(human, msg)
    if human.familyUuid == "" then
        Broadcast.sendBroadcast(human, Lang.MOUSE, Lang.FAMILY_NOT_EXIST)
        return
    end
    local nSend2Ldata = {
            type = 13,
    }
    local contribute 
    if msg.free == 1 then
        if os.time() - human.db.taoyuanLastFreeTime < FamilyDefine.FAMILY_TAOYUAN_FREE_COOLDOWN then
            Broadcast.sendBroadcast(human, Lang.MOUSE, Lang.FAMILY_TAOYUAN_COOLDOWN)
            return
        end
        human.db.taoyuanLastFreeTime = os.time()
        nSend2Ldata.free = 1
        
        contribute = FamilyDefine.FAMILY_TAOYUAN_FREE_CONTRIBUTE
        updateFamilyContribution(human, contribute)
        InnerDataManagerFL.Send2WInnerData(human, InnerDataDefine.INNERDATA_TYPE_FAMILY, nSend2Ldata)
    else
        if ObjHuman.getYuanbao(human) < FamilyDefine.FAMILY_TAOYUAN_YB then
            Broadcast.sendBroadcast(human, Lang.MOUSE, Lang.OFFLINE_PK_NO_RMB_FOR_CD)
            ShopHelp.onNoRMB(human)
            return
        end
        ObjHuman.decYuanbao(human, FamilyDefine.FAMILY_TAOYUAN_YB, "familytaoyuan")       
        contribute = FamilyDefine.FAMILY_TAOYUAN_YB_CONTRIBUTE
        updateFamilyContribution(human, contribute)
        InnerDataManagerFL.Send2WInnerData(human, InnerDataDefine.INNERDATA_TYPE_FAMILY, nSend2Ldata)        
    end
    Broadcast.sendBroadcast(human, Lang.MOUSE, string.format(Lang.FAMILY_TAOYUAN_OK, contribute))    
    
    local mm = Msg.gc.GC_FAMILY_ACT_TY_GIVE
    mm.free = msg.free
    Msg.send(mm, human.fd)
    OfficialLogic.checkOneCondition(human, "taoyuanTimes")
end


function onGetOnHookBuyTime(human, nVipLv)
    return VipLogic.getVipTimes(human, VipDefine.VIP_PRIVILEGR_FAMILYONHOOK, nVipLv)
end

function onGetOnHookLeftTime(human)
    return FamilyOnHookConfig.freeTime + human.db.familyOnHookBuyTime * 3600 - human.db.familyOnHookTime
end

function onSendOnHookTime(human)
    local nSendMsg = Msg.gc.GC_FAMILY_ACT_ONHOOKTIME
    nSendMsg.leftTime = onGetOnHookLeftTime(human)
    Msg.send(nSendMsg, human.fd)
end


function W2LProcess(human, oType, oData)
    if oData.type == 20 then             --创建军团
        if oData.iscreate == 1 then
            if oData.createType == 0 then
                human.db.precost_yinliang = human.db.precost_yinliang - FamilyCreateConfig.needYinliang
                if oData.result == 0 then
                    ObjHuman.decYinliang(human, FamilyCreateConfig.needYinliang, "family_create")
                    human.familyUuid = oData.familyUuid
                    human.familyName = oData.familyName
                    ObjHuman.doCalc(human)
                end
            else
                human.db.precost_yuanbao = human.db.precost_yuanbao -  FamilyCreateConfig.yuanbao
                if oData.result == 0 then
                    ObjHuman.decYuanbao(human, FamilyCreateConfig.yuanbao, "family_create")
                    human.familyUuid = oData.familyUuid
                    human.familyName = oData.familyName
                    ObjHuman.doCalc(human)
                end
            end
        else
            human.familyUuid = oData.familyUuid
            human.familyName = oData.familyName
            ObjHuman.doCalc(human)
            
            FamilyLogicFL.checkFamilyWarResult(human)
        end
    elseif oData.type == 21 then
        human.familyUuid = ""
        human.familyname = ""
        ObjHuman.doCalc(human)
        
        FamilyLogicFL.checkFamilyWarResult(human)
        --elseif oData.type == 4 then         --查询仓库
        --    local msgList = Msg.gc.GC_FAMILY_STORE_LIST
        --    msgList.cap = oData.data.cap
        --    GridLogic.makeList(human, oData.data.familystore, msgList.cap, msgList, Msg.gc.GC_FAMILY_STORE_CLEAR)
    elseif oData.type == 5 then         --存放仓库成功
        if oData.data.result == 0 then
            BagLogic.delGridByIndex(human, oData.data.bagIndex, "family_store")
        end
    elseif oData.type == 6 then         --仓库提取成功
        if oData.data.result == 0 then
            BagLogic.addItemByGrid(human, oData.data.bagIndex, oData.data.griddata, "family_store")
        end
    elseif oData.type == 8 then         --军团升级
        for _, member in ipairs(oData.memberList) do
            local target = ObjHuman.onlineUuid[member.uuid]
            if target and target.familyUuid == oData.familyUuid then
                ObjHuman.doCalc(target)
                OfficialLogic.checkOneCondition(target, "familyLv")                
            end
        end
    elseif oData.type == 11 then        --退出军团
        human.familyUuid = ""
        human.familyname = ""
        FamilyLogicFL.checkFamilyWarResult(human)
        ObjHuman.doCalc(human)
    elseif oData.type == 12 then        --军团军旗进阶成功并且升级了
        for _, member in ipairs(oData.memberList) do
            local target = ObjHuman.onlineUuid[member.uuid]
            if target and target.familyUuid == oData.familyUuid then
                ObjHuman.doCalc(target)
            end
        end
    elseif oData.type == 13 then  -- 开启军团副本成功
         human.db.precost_yuanbao = human.db.precost_yuanbao -  FamilyDefine.FAMILY_COPY_YUANBAO
         if human.db.precost_yuanbao < 0 then
            human.db.precost_yuanbao = 0
         end
         if oData.result == 1 then
            ObjHuman.decYuanbao(human, FamilyDefine.FAMILY_COPY_YUANBAO, "family_copy")
         end
    elseif oData.type == 14 then -- 添加跨服霸主
         FamilyLogicFL.createFamilyWarWinner(oData.result)
    elseif oData.type == 15 then 
         FamilyLogicFL.checkAllUserFamilyWarResult()      
    elseif oData.type == 16 then
         FamilyLogicFL.familyTaoyuanGet(human, oData.index, oData.good)   
    else
        local familyid = oData.familyid
        local newLeaderUuid = oData.newLeaderUuid
        local familyname = oData.familyname
        local allyname = oData.allyname

        -- title change 1
        local titleMsg = Msg.gc.GC_FAMILY_TITLE_CHANGE
        titleMsg.objID = human.id
        titleMsg.familyUuid = familyid
        titleMsg.familyName = familyname
        titleMsg.familyOfficial = FamilyDefine.OFFICIAL_NORMAL
        titleMsg.allyName = allyname
        Obj.sendArea(titleMsg, human.scene_id, human.x, human.y)

        -- title change 2
        newLeader = ObjHuman.onlineUuid[newLeaderUuid]
        if newLeader then
            titleMsg.objID = newLeader.id
            titleMsg.familyUuid = familyid
            titleMsg.familyName = familyname
            titleMsg.familyOfficial = FamilyDefine.OFFICIAL_LEADER
            titleMsg.allyName = allyname
            Obj.sendArea(titleMsg, newLeader.scene_id, newLeader.x, newLeader.y)
        end
    end
end

function OnInit()
    RandomShop = {}
    for k, v in ipairs(ShopExcel) do
        if v.type == 0 then
            v.index = k
            table.insert(RandomShop, v)
        end
    end
end

InnerDataManagerFL.Register(InnerDataDefine.INNERDATA_TYPE_FAMILY, W2LProcess)
OnInit()
